#include <stdio.h>
#include <string.h>
#include "sle_server.h"
#include "cmsis_os2.h"
#include "ohos_init.h"
#include "errcode.h"
#include "wifi_connecter.h"
#include "iot_config.h"
#include "iot_mqtt.h"
#include "cjson_init.h"
#include "iot_profile.h"


#define TASK_SLEEP_1000MS (1000)
#define CN_COMMAND_INDEX                    "commands/request_id="

#if CHIP_WS63
#define STACK_SIZE 10240
#define MAX_CONNECT_RETRY_TIMES 16
#define CONNECT_ATTEMPT_INTERVAL_MS 300
#else
#define ATTR.STACK_SIZE 10240
#endif


static void DemoMsgRcvCallBack(int qos, char *topic, char *payload)
{
    const char *requesID;
    char *tmp;
    IoTCmdResp resp;
    printf("RCVMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", qos, topic, payload);
    /* app 下发的操作 */
    //TrafficLightMsgRcvCallBack(payload);
    tmp = strstr(topic, CN_COMMAND_INDEX);
    if (tmp != NULL) {
        // /< now you could deal your own works here --THE COMMAND FROM THE PLATFORM
        // /< now er roport the command execute result to the platform
        requesID = tmp + strlen(CN_COMMAND_INDEX);
        resp.requestID = requesID;
        resp.respName = NULL;
        resp.retCode = 0;   ////< which means 0 success and others failed
        resp.paras = NULL;
        (void)IoTProfileCmdResp(CONFIG_DEVICE_PWD, &resp);
    }
}

static void RSUTrafficTask(char* arg)
{
    (void)arg;
        // setup your AP params
    // 设置AP参数，包括SSID、预共享密钥、安全类型（PSK）、netID
    WifiDeviceConfig apConfig = {
        .ssid = CONFIG_AP_SSID,
        .preSharedKey = CONFIG_AP_PWD,
        .securityType = WIFI_SEC_TYPE_PSK
    };

    int netId = -1;

    // demo启动时，系统的WiFi功能可能没有初始化完毕，需要等待不确定的时候。待优化。
    for (uint8_t i = 0; i < MAX_CONNECT_RETRY_TIMES; i++) {
        osDelay(CONNECT_ATTEMPT_INTERVAL_MS);
        netId = ConnectToHotspot(&apConfig);
        if (netId >= 0) {
            break;
        }
    }

    sle_server_init();

    printf("sle init success\r\n");
    usleep(3000000);
    printf("start mqtt\r\n");

    CJsonInit();
    IoTMain();
    IoTSetMsgCallback(DemoMsgRcvCallBack);
    TimeDelaySeconds(3);//TaskMsleep(30000); // 30000 = 3s连接华为云

    char payload[16];
    for (int i = 0; i < 10; i += 1) {
        // publish message to broker
        snprintf(payload, 16, "message-%d", i);
        IotSendMsg(0, "RSU", payload);
        printf("mqtt sent: %s", payload);
        usleep(1000000);
    }
    
    // MQTTClient client;
    // MqttInit(&client);
    // MqttSubscribe(client, on_message);

}

static void RSUTrafficEntry(void)
{
    osThreadAttr_t attr;

    attr.name = "RSUTrafficTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 10240;
    attr.priority = 25;

    if (osThreadNew(RSUTrafficTask, NULL, &attr) == NULL) {
       printf("[RSUTrafficEntry] Falied to create RSUTrafficTask!\n");
    }else printf("[RSUTrafficEntry]  create RSUTrafficTask successfully !\n");
}

SYS_RUN(RSUTrafficEntry); // if test add it